package com.example.research.service;

import com.example.research.dto.AuditRequest;
import com.example.research.dto.PendingAuditItem;
import com.example.research.dto.AuditHistoryItem;
import com.example.research.entity.AuditRecord;
import com.example.research.entity.User;
import com.example.research.entity.VerticalProject;
import com.example.research.entity.HorizontalProject;
import com.example.research.entity.Paper;
import com.example.research.mapper.AuditRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.ArrayList;

/**
 * 审核服务类
 */
@Service
@Transactional
public class AuditService {

    @Autowired
    private AuditRecordMapper auditRecordMapper;

    @Autowired
    private VerticalProjectService verticalProjectService;

    @Autowired
    private HorizontalProjectService horizontalProjectService;

    @Autowired
    private PaperService paperService;

    @Autowired
    private UserService userService;

    /**
     * 根据ID查询审核记录
     */
    public AuditRecord findById(Long id) {
        return auditRecordMapper.selectById(id);
    }

    /**
     * 查询所有审核记录
     */
    public List<AuditRecord> findAll() {
        return auditRecordMapper.selectAll();
    }

    /**
     * 根据审核人ID查询审核记录
     */
    public List<AuditRecord> findByAuditorId(Long auditorId) {
        return auditRecordMapper.selectByAuditorId(auditorId);
    }

    /**
     * 根据成果类型和成果ID查询审核记录
     */
    public List<AuditRecord> findByAchievement(Integer achievementType, Long achievementId) {
        return auditRecordMapper.selectByAchievement(achievementType, achievementId);
    }

    /**
     * 根据审核状态查询审核记录
     */
    public List<AuditRecord> findByAuditStatus(Integer auditStatus) {
        return auditRecordMapper.selectByAuditStatus(auditStatus);
    }

    /**
     * 获取待审核的项目列表
     */
    public List<PendingAuditItem> getPendingAuditItems() {
        List<PendingAuditItem> pendingItems = new ArrayList<>();

        // 获取待审核的纵向课题
        List<VerticalProject> pendingVerticalProjects = verticalProjectService.findByAuditStatus(0);
        for (VerticalProject project : pendingVerticalProjects) {
            PendingAuditItem item = new PendingAuditItem();
            item.setId(project.getId());
            item.setTitle(project.getProjectName());
            item.setType("vertical");
            item.setSubmitterName(project.getUser() != null ? project.getUser().getRealName() : "");
            item.setSubmitterDepartment(project.getUser() != null ? project.getUser().getDepartment() : "");
            item.setSubmitTime(project.getCreatedTime());
            item.setAuditStatus("待审核");
            item.setProjectLevel(project.getProjectLevel());
            item.setTotalAmount(project.getTotalAmount() != null ? project.getTotalAmount().doubleValue() : null);
            item.setApprovalDepartment(project.getApprovalDepartment());
            item.setProjectLeader(project.getProjectLeader());
            pendingItems.add(item);
        }

        // 获取待审核的横向课题
        List<HorizontalProject> pendingHorizontalProjects = horizontalProjectService.findByAuditStatus(0);
        for (HorizontalProject project : pendingHorizontalProjects) {
            PendingAuditItem item = new PendingAuditItem();
            item.setId(project.getId());
            item.setTitle(project.getProjectName());
            item.setType("horizontal");
            item.setSubmitterName(project.getUser() != null ? project.getUser().getRealName() : "");
            item.setSubmitterDepartment(project.getUser() != null ? project.getUser().getDepartment() : "");
            item.setSubmitTime(project.getCreatedTime());
            item.setAuditStatus("待审核");
            item.setContractAmount(project.getContractAmount() != null ? project.getContractAmount().doubleValue() : null);
            item.setPartyName(project.getPartyName());
            item.setProjectLeader(project.getProjectLeader());
            item.setExecutionLeader(project.getExecutionLeader());
            pendingItems.add(item);
        }

        // 获取待审核的论文
        List<Paper> pendingPapers = paperService.findByAuditStatus(0);
        for (Paper paper : pendingPapers) {
            PendingAuditItem item = new PendingAuditItem();
            item.setId(paper.getId());
            item.setTitle(paper.getPaperTitle());
            item.setType("paper");
            item.setSubmitterName(paper.getUser() != null ? paper.getUser().getRealName() : "");
            item.setSubmitterDepartment(paper.getUser() != null ? paper.getUser().getDepartment() : "");
            item.setSubmitTime(paper.getCreatedTime());
            item.setAuditStatus("待审核");
            item.setJournalName(paper.getJournalName());
            item.setIndexLevel(paper.getIndexLevel());
            item.setFirstAuthor(paper.getFirstAuthor());
            item.setCorrespondingAuthor(paper.getCorrespondingAuthor());
            item.setImpactFactor(paper.getImpactFactor() != null ? paper.getImpactFactor().doubleValue() : null);
            pendingItems.add(item);
        }

        return pendingItems;
    }

    /**
     * 获取审核历史记录列表
     */
    public List<AuditHistoryItem> getAuditHistoryItems() {
        List<AuditHistoryItem> historyItems = new ArrayList<>();
        List<AuditRecord> auditRecords = auditRecordMapper.selectAll();

        for (AuditRecord record : auditRecords) {
            AuditHistoryItem item = new AuditHistoryItem();
            item.setId(record.getId());
            item.setAuditTime(record.getAuditTime());
            item.setAuditComment(record.getAuditComment());
            item.setAuditorName(record.getAuditor() != null ? record.getAuditor().getRealName() : "");

            // 根据审核状态设置状态文本
            if (record.getAuditStatus() == 0) {
                item.setAuditStatus("待审核");
            } else if (record.getAuditStatus() == 1) {
                item.setAuditStatus("已通过");
            } else if (record.getAuditStatus() == 2) {
                item.setAuditStatus("已拒绝");
            }

            // 根据成果类型获取项目信息
            if (record.getAchievementType() == 1) { // 纵向课题
                item.setType("vertical");
                VerticalProject project = verticalProjectService.findById(record.getAchievementId());
                if (project != null) {
                    item.setTitle(project.getProjectName());
                    item.setSubmitterName(project.getUser() != null ? project.getUser().getRealName() : "");
                }
            } else if (record.getAchievementType() == 2) { // 横向课题
                item.setType("horizontal");
                HorizontalProject project = horizontalProjectService.findById(record.getAchievementId());
                if (project != null) {
                    item.setTitle(project.getProjectName());
                    item.setSubmitterName(project.getUser() != null ? project.getUser().getRealName() : "");
                }
            } else if (record.getAchievementType() == 3) { // 论文
                item.setType("paper");
                Paper paper = paperService.findById(record.getAchievementId());
                if (paper != null) {
                    item.setTitle(paper.getPaperTitle());
                    item.setSubmitterName(paper.getUser() != null ? paper.getUser().getRealName() : "");
                }
            }

            historyItems.add(item);
        }

        return historyItems;
    }

    /**
     * 提交审核
     */
    public void submitForAudit(AuditRequest auditRequest, Long auditorId) {
        // 创建审核记录
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setAchievementType(auditRequest.getAchievementType());
        auditRecord.setAchievementId(auditRequest.getAchievementId());
        auditRecord.setAuditorId(auditorId);
        auditRecord.setAuditStatus(auditRequest.getAuditStatus());
        auditRecord.setAuditComment(auditRequest.getAuditComment());

        // 插入审核记录
        auditRecordMapper.insert(auditRecord);

        // 更新对应成果的审核状态
        updateAchievementAuditStatus(auditRequest.getAchievementType(),
                                   auditRequest.getAchievementId(),
                                   auditRequest.getAuditStatus(),
                                   auditRequest.getAuditComment());
    }

    /**
     * 审核通过
     */
    public void approve(Integer achievementType, Long achievementId, String comment, Long auditorId) {
        // 检查教师是否有权限审核该成果
        if (!canAuditAchievement(achievementType, achievementId, auditorId)) {
            throw new RuntimeException("您无权限审核该成果，只能审核您负责学生的成果");
        }

        AuditRequest auditRequest = new AuditRequest();
        auditRequest.setAchievementType(achievementType);
        auditRequest.setAchievementId(achievementId);
        auditRequest.setAuditStatus(1); // 审核通过
        auditRequest.setAuditComment(comment);

        submitForAudit(auditRequest, auditorId);
    }

    /**
     * 审核拒绝
     */
    public void reject(Integer achievementType, Long achievementId, String comment, Long auditorId) {
        // 检查教师是否有权限审核该成果
        if (!canAuditAchievement(achievementType, achievementId, auditorId)) {
            throw new RuntimeException("您无权限审核该成果，只能审核您负责学生的成果");
        }

        AuditRequest auditRequest = new AuditRequest();
        auditRequest.setAchievementType(achievementType);
        auditRequest.setAchievementId(achievementId);
        auditRequest.setAuditStatus(2); // 审核拒绝
        auditRequest.setAuditComment(comment);

        submitForAudit(auditRequest, auditorId);
    }

    /**
     * 更新成果的审核状态
     */
    private void updateAchievementAuditStatus(Integer achievementType, Long achievementId,
                                            Integer auditStatus, String auditComment) {
        switch (achievementType) {
            case 1: // 纵向课题
                verticalProjectService.updateAuditStatus(achievementId, auditStatus, auditComment);
                break;
            case 2: // 横向课题
                horizontalProjectService.updateAuditStatus(achievementId, auditStatus, auditComment);
                break;
            case 3: // 论文
                paperService.updateAuditStatus(achievementId, auditStatus, auditComment);
                break;
            default:
                throw new RuntimeException("不支持的成果类型");
        }
    }

    /**
     * 获取待审核的成果列表
     */
    public List<AuditRecord> getPendingAudits() {
        return auditRecordMapper.selectByAuditStatus(0);
    }

    /**
     * 获取审核历史
     */
    public List<AuditRecord> getAuditHistory(Integer achievementType, Long achievementId) {
        return auditRecordMapper.selectByAchievement(achievementType, achievementId);
    }

    /**
     * 检查用户是否有权限审核该成果
     * 系统管理员可以审核所有成果，教师只能审核自己负责学生的成果
     */
    private boolean canAuditAchievement(Integer achievementType, Long achievementId, Long auditorId) {
        try {
            // 获取审核者信息
            User auditor = userService.findById(auditorId);
            if (auditor == null) {
                return false;
            }

            // 系统管理员可以审核所有成果
            if (auditor.isAdmin()) {
                return true;
            }

            // 教师只能审核自己负责学生的成果
            if (!auditor.isTeacher()) {
                return false;
            }

            // 根据成果类型获取成果的创建者
            Long achievementUserId = null;
            switch (achievementType) {
                case 1: // 纵向课题
                    VerticalProject vp = verticalProjectService.findById(achievementId);
                    if (vp != null) {
                        achievementUserId = vp.getUserId();
                    }
                    break;
                case 2: // 横向课题
                    HorizontalProject hp = horizontalProjectService.findById(achievementId);
                    if (hp != null) {
                        achievementUserId = hp.getUserId();
                    }
                    break;
                case 3: // 论文
                    Paper paper = paperService.findById(achievementId);
                    if (paper != null) {
                        achievementUserId = paper.getUserId();
                    }
                    break;
                default:
                    return false;
            }

            if (achievementUserId == null) {
                return false;
            }

            // 检查成果创建者是否是该教师负责的学生
            User achievementUser = userService.findById(achievementUserId);
            if (achievementUser == null || !achievementUser.isStudent()) {
                return false;
            }

            // 检查学生的teacher_id是否等于审核者的ID
            String studentTeacherId = achievementUser.getTeacherId();
            return studentTeacherId != null && auditorId.toString().equals(studentTeacherId);

        } catch (Exception e) {
            return false;
        }
    }
}
